#include "mylist.h"
#include <QEvent>
#include <QApplication>
#include <QMouseEvent>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QDrag>



MyList::MyList(QWidget *parent /*parent = 0*/)
    :QListWidget (parent)
{
    setAcceptDrops(true);
}

void MyList::mousePressEvent(QMouseEvent *event)
{

    if (event->button() == Qt::LeftButton)
        startPos = event->pos();
    QListWidget::mousePressEvent(event);
}

void MyList::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
            int distance = (event->pos() - startPos).manhattanLength();
            if (distance >= QApplication::startDragDistance())
                performDrag();
        }
        QListWidget::mouseMoveEvent(event);
}

void MyList::dragEnterEvent(QDragEnterEvent *event)
{
    QListWidget::dragEnterEvent(event);
    event->accept(); // 通过事件的接收，激活后续配合的函数dragMoveEvent、dropEvent
//    event->ignore();
    //accept 事件传递到此处，事件不再向后（父窗口）传递,同时激活
    //ignore 事件传递到此，
}

void MyList::dragMoveEvent(QDragMoveEvent *event)
{
    QObject *source = event->source();
        if (source && source != this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        }
}

void MyList::dropEvent(QDropEvent *event)
{
   QObject *source = event->source();
        if (source && source != this) {
            addItem(event->mimeData()->text());
            event->setDropAction(Qt::MoveAction);
            event->accept();
        }
}

void MyList::performDrag()
{
    QListWidgetItem *item = currentItem();
        if (item) {
            QMimeData *mimeData = new QMimeData;
            mimeData->setText(item->text());

            QDrag *drag = new QDrag(this);
            drag->setMimeData(mimeData);
            drag->setPixmap(QPixmap(":/images/person.png"));
            if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
                delete item;
        }
}
